import { connect } from 'umi';

import React, { useState, useEffect, useRef } from 'react';
import styles from './index.less';
import { Slider } from 'antd';
import { layerUtils, viewUtils } from '@/utils/arcgis';
import cls from 'classnames';
// import WidgetPanel from '@/components/containers/widgetPanel';
import { CloseOutlined } from '@ant-design/icons';
import { useThrottle } from 'react-use';
import { message } from 'antd';

const BaseMapGallery = ({ onClose, basemapIndex }) => {
  // 设定当前选中的是哪个底图
  const [currentIndex, setCurrentIndex] = useState();
  const [curSliderValue, setCurSliderValue] = useState(0);
  const _curSliderValue = useThrottle(curSliderValue, 300);
  const isInitRef = useRef(false);
  const extraLayerRef = useRef({});

  let defaultInitValue = 0;

  // 组件挂载时，检测底图是否被设置过透明度，
  if (!isInitRef.current) {
    try {
      // 设置滑块初始值
      defaultInitValue = Math.round((1 - window.agsGlobal.view.map.ground.opacity) * 100);
    } catch (error) {
      console.log(error);
    }
  }

  useEffect(() => {
    // 第一次渲染 设置上次用户选择值，并在下一次渲染中阻止修改地图透明度
    setCurSliderValue(defaultInitValue);
    let timer = setTimeout(() => {
      // 解除阻止修改地图透明度
      isInitRef.current = true;
    }, 20);
    return () => clearTimeout(timer);
  }, []);

  // 根据全局配置state配置，初始化赋值
  useEffect(() => {
    setCurrentIndex(basemapIndex);
  }, [basemapIndex]);

  // 根据限流后滑条的值修改地图透明度
  useEffect(() => {
    if (!isInitRef.current) return;
    // 100%透明
    // 0不透明
    let curOpacity = 1 - _curSliderValue / 100;
    window.agsGlobal.view.map.basemap.baseLayers.items[0].opacity = curOpacity;
    window.agsGlobal.view.map.ground.opacity = curOpacity;
    setExtraLayerOpacity('Google影像', curOpacity);
  }, [_curSliderValue]);

  async function setExtraLayerOpacity(name, opacity) {
    if (!extraLayerRef.current[name]) {
      const view = await viewUtils.isViewReady();
      extraLayerRef.current[name] = layerUtils.getLayerByTitle(view, name);
    }
    if (extraLayerRef.current[name]) {
      extraLayerRef.current[name].opacity = opacity;
    }
  }

  const handleSwitchBmap = async e => {
    let _currentIndex = currentIndex;
    const index = +e.target.dataset.i;
    if (index === currentIndex) return;
    try {
      setCurrentIndex(index);
      const basemap = await viewUtils.createBasemap(window.basemapConfig[index]);
      window.agsGlobal.view.map.basemap = basemap;
    } catch (error) {
      console.error(error);
      setCurrentIndex(_currentIndex);
      message.error('切换底图失败，请等底图初始化完毕后操作');
    }
  };

  const renderItem = () => {
    return window.basemapConfig.map((item, i) => {
      return (
        <div
          key={item.title}
          className={cls(styles.item, {
            [styles.itemActive]: i === currentIndex,
          })}
        >
          <img
            title={item.title}
            src={item.iconUrl}
            alt=""
            className={styles.icon}
            // data-itemid={item.id}
            data-i={i}
            onClick={handleSwitchBmap}
          />
        </div>
      );
    });
  };

  // 透明度滚动条
  function handleSliderChange(value) {
    setCurSliderValue(value);
  }

  return (
    <div className={cls(styles.panel, 'base-panel')}>
      <div className={'base-panel-title'}>
        底图切换
        <span className={'base-panel-title-btn'}>
          <CloseOutlined onClick={onClose} />
        </span>
      </div>
      <div className="base-panel-body" style={{ height: 332 }}>
        <div className={styles.container}>{renderItem()}</div>
        <div className={styles.slider}>
          底图透明度
          <Slider
            marks={{
              100: '100',
              75: '75',
              50: '50',
              25: '25',
              0: '0',
            }}
            // defaultValue={0}
            defaultValue={defaultInitValue}
            onChange={handleSliderChange}
          />
        </div>
      </div>
    </div>
  );
};

// export default BaseMapGallery;
export default connect(({ app }) => {
  return { basemapIndex: app.basemapIndex };
})(BaseMapGallery);
